package com.springboot.myspringboot.controller;

import com.springboot.myspringboot.Service.UserService;
import com.springboot.myspringboot.config.Result;
import com.springboot.myspringboot.entity.User;
import com.springboot.myspringboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired
    UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder; //注入bcryct加密

    @PostMapping("login")
    public Result<?> login(@RequestBody User user, HttpSession session){

        try {
            User res = userService.selectOne(user);
            if(res == null){
                return Result.error("400", "账号不存在或密码错误");
            }
            log.info("登录login");
            String encode = bCryptPasswordEncoder.encode(res.getPassword());
            Boolean eq = bCryptPasswordEncoder.matches(user.getPassword(), encode);
            if(eq){
                String token = TokenUtils.genToken(res);
                session.setAttribute("loginUser", res);
                res.setToken(token);
                return Result.success(res);
            }else {
                return Result.error("400", "密码错误");
            }
        }catch (Exception e){
            return Result.error("500", "服务器错误了");
        }
    }
}
